package api

import (
	"game-handker/api/dbinit"
	"game-handker/restapi"
	"net/http"

	"github.com/gin-gonic/gin"
)

// Game 定义游戏表的结构体
type Game struct {
	ID             uint   `gorm:"primaryKey;autoIncrement" json:"id"`
	GameName       string `gorm:"column:game_name" json:"gameName"`
	GameVersion    string `gorm:"column:game_version" json:"gameVersion"`
	StaticResource string `gorm:"column:static_resource" json:"staticResource"`
}

func (Game) TableName() string {
	return "games_info"
}
func init() {
	dbinit.Init()
	dbinit.DB.AutoMigrate(&Game{})
}

func QueryStaticResources() gin.HandlerFunc {
	return func(c *gin.Context) {

		var req struct {
			GameName    string `json:"gameName" binding:"required"`
			GameVersion string `json:"gameVersion" binding:"required"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			restapi.FailResponse(c, err.Error(), http.StatusBadRequest)
			c.JSON(400, gin.H{"error": err.Error()})
			return
		}

		var games []Game
		if err := dbinit.DB.Where("game_name = ? AND game_version = ?", req.GameName, req.GameVersion).Find(&games).Error; err != nil {
			restapi.FailResponse(c, "failed to query database", http.StatusInternalServerError)
			return
		}

		var staticResources []string
		for _, game := range games {
			staticResources = append(staticResources, game.StaticResource)
		}
		restapi.OkResponse(c, gin.H{"resources": staticResources})
	}
}

func AddStaticResources() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 接收请求参数
		var games []Game
		if err := c.ShouldBindJSON(&games); err != nil {
			restapi.FailResponse(c, err.Error(), http.StatusBadRequest)
			return
		}
		dbinit.DB.Create(&games)

		// 返回结果
		restapi.OkResponse(c, gin.H{"games": games})
	}
}
